package 验证二叉搜索树;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 验证二叉搜索树
 * 递归
 * @date 2022/11/6 14:38
 */
public class Demo98 {
    // 记录前一个节点，前一个结点一定是全局变量，不然会有问题
    static TreeNode pre;
    public static void main(String[] args) {
        TreeNode root=new TreeNode(5);
        root.left=new TreeNode(4);
        root.right=new TreeNode(6);
        root.right.left=new TreeNode(3);
        root.right.right=new TreeNode(7);
        boolean validBST = isValidBST(root);
    }

    //确实递归函数
    public static boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        // 左
        boolean left = isValidBST(root.left);
        // 中
        if (pre != null && root.val <= pre.val) {
            return false;
        }
        pre = root;
        // 右
        boolean right = isValidBST(root.right);
        return right&&left;
    }



    //Definition for a binary tree node.
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) {
            this.val = val;}
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
